package com.micro.magupe.sharding.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Map;
import java.util.logging.Logger;

import javax.sql.DataSource;

import com.micro.magupe.sharding.core.util.ReflectiveUtil;

public abstract class AbstractDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable{

	private final Map<String, DataSource> dataSourceMap;
	
	private PrintWriter logWriter = new PrintWriter(System.out);
	
    public AbstractDataSource(final Map<String, DataSource> dataSourceMap) throws SQLException {
        this.dataSourceMap = dataSourceMap;
    }
    
	public Map<String, DataSource> getDataSourceMap() {
		return dataSourceMap;
	}
	
	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
	}
	
	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return logWriter;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		this.logWriter = new PrintWriter(System.out);
	}
	
    @Override
    public final Connection getConnection(final String username, final String password) throws SQLException {
        return getConnection();
    }
    
    public void close() {
        closeOriginalDataSources();
    }
    
    private void closeOriginalDataSources() {
        if (null != dataSourceMap) {
            closeDataSource(dataSourceMap);
        }
    }
    
    private void closeDataSource(final Map<String, DataSource> dataSourceMap) {
        for (DataSource each : dataSourceMap.values()) {
            try {
            	ReflectiveUtil.findMethod(each, "close").invoke(each);
            } catch (final ReflectiveOperationException ignored) {
            }
        }
    }
}
